package model;

import constant.Constants;

import java.util.Random;
import java.util.concurrent.*;

public class CustomerSessions {

    private ConcurrentHashMap<Integer, Session> sessions = new ConcurrentHashMap<>();
    private ScheduledExecutorService sessionCleaner = Executors.newSingleThreadScheduledExecutor();

    public CustomerSessions() {
        // 启动定时任务，定期清理过期的会话
        sessionCleaner.scheduleAtFixedRate(this::cleanExpiredSessions, 1, 1, TimeUnit.MINUTES);
    }

    /**
     * 获取或创建一个会话(会话没有过期则返回旧的 否则创建一个新的)
     * @param customerId 客户ID
     * @return 会话
     */
    public Session getOrCreateSession(int customerId) {
        return sessions.compute(customerId, (id, session) -> {
            if (session == null || System.currentTimeMillis() > session.getExpirationTime()) {
                session = new Session(this.generateSessionKey(), System.currentTimeMillis() + Constants.TEN_MINUTES);
            }
            return session;
        });
    }

    public void removeSession(int customerId) {
        sessions.remove(customerId);
    }

    public ConcurrentMap<Integer, Session> getSessions() {
        return sessions;
    }

    // 该函数用于生成一个8位的随机会话密钥，由数字和大写字母组成
    private String generateSessionKey() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            char c = (char) (random.nextInt(36) < 10 ? random.nextInt(10) + '0' : random.nextInt(26) + 'A');
            sb.append(c);
        }
        return sb.toString();
    }

    private void cleanExpiredSessions() {
        long currentTime = System.currentTimeMillis();
        sessions.entrySet().removeIf(entry -> currentTime > entry.getValue().getExpirationTime());
    }
}